package no.truben.kroken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

import javax.swing.JOptionPane;

import no.truben.kroken.io.PluginReader;

public class Kroken {

	static Map<String, Archive> extensions;
	
	public static void main(String[] args) {
		JOptionPane.showMessageDialog(null, args);
		extensions = PluginReader.readPlugins("./Plugins");
		for(String file:args) {
			String ext = file.substring(file.lastIndexOf('.')+1).toLowerCase();
			
			if(extensions.containsKey(ext)) {
				Archive arc = extensions.get(ext);
				try {
					String line;
					Process p = Runtime.getRuntime().exec(produceExeString(arc.getPath(),file,ext,null));
					BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
				    while ((line = input.readLine()) != null) {
				        System.out.println(line);
				    }
				    input.close();

				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			else
				JOptionPane.showMessageDialog(null, "We currently do not support '" + ext + "'.");
			
		}

	}
	
	private static String[] produceExeString(String exec, String file, String ext, String dir) {
		exec = exec.trim();
		exec = exec.replaceAll("  ", " ");
		String par[] = exec.split(" ");
		for (int i = 0; i < par.length; i++) {
			String s = par[i];
			s = s.replaceAll("%filename%", file);
			s = s.replaceAll("%extension%", ext);
			s = s.replaceAll("%dir%", dir);
			par[i] = s;
		}
		return par;
	}
}
